package w83b.w83bOperacionesPaso.w83bImpugnaciones;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


import es.ejie.frmk.presentacion.operacion.paso.Q70ActionPasoOP;
import es.ejie.frmk.presentacion.sesiondatos.Q70ContextoEJIE;

public class W83bDescargarDocumentoContextoOPAction extends Q70ActionPasoOP {

	protected void processOP(Q70ContextoEJIE contexto, ActionErrors errores, ActionMapping mapping,
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
	}

	protected ActionForward processForward(Q70ContextoEJIE contexto, ActionErrors errors, ActionMapping mapping, 
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		
			if (StringUtils.isNotEmpty(request.getParameter("idDocumentoContexto")))
			{
				String idDocumento=request.getParameter("idDocumentoContexto");
				
				
				HashMap datos=(HashMap)contexto.get("w83bMapaFileImpugnaciones");
				HashMap documento=(HashMap)datos.get("file_"+idDocumento);
				InputStream in=(InputStream) documento.get("documentoStream");
				
				ServletOutputStream out = response.getOutputStream();
				
				//se vuelcan los bytes a una variable pero en el documento en sí, el input se va a vaciar,
				byte[] bytes=IOUtils.toByteArray(in);
				
				in.close();
				
				response.setContentType("application/octet-stream");
			    response.setHeader("Content-Disposition","attachment;filename=\""+documento.get("nombreDocumento")+"\"");
						
				
			   for(int i=0;i<bytes.length;i++)
			   {
				   out.write(bytes[i]);
			   }
			 //para no perder el inputStream del docuemtno, volcamos los bytes al documento en sí
			   ByteArrayInputStream in2= new ByteArrayInputStream(bytes);
			   in2.close();
			   documento.put("documentoStream",(InputStream) in2);
			   
			     
			   out.flush();
			   out.close();
			
			      return null;
				
			}
		
		return mapping.findForward("error");	
		
	}
}

